﻿

-- =============================================
-- Author:		Popa Dorin
-- Create date: 01.03.2014
-- Description:	Populeaza tabela de conturi pentru o unitate noua
-- =============================================
CREATE PROCEDURE [dbo].[balcon_PopuleazaConturiUnitateNoua]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	DECLARE @DataPlanConturi datetime
	SET NOCOUNT ON;
	BEGIN TRAN
	
	SET @DataPlanConturi = '2000-1-1';
	
	SELECT TOP 1 @DataPlanConturi =MIN(DataAplicare)  FROM PlanConturi pc
	JOIN [BalconSetup] b On b.CodUnitate = @CodUnitate AND pc.TipUnitate=b.TipUnitate 
	Where YEAR(DataAplicare)*100 + MONTH(DataAplicare) >= b.AnCurent*100+b.LunaCurenta
	

	PRINT('NETERMINALE')
    --copiaza conturile neterminale
	INSERT INTO [Conturi]([Cont],[Denumire],[Tip],[Terminal],[ContParinte],[EsteAnalitic],[Categorie],[CodUnitate],[DebitInitial],[CreditInitial],[DebitPrecedent],[CreditPrecedent],[RulajDebit] ,[RulajCredit])
         SELECT DISTINCT [Cont],[Denumire],[Tip],[Terminal],[ContParinte],0,[Categorie],@CodUnitate,0,0,0,0,0,0 FROM [PlanConturi] pc
         JOIN BalconSetup b ON [DataAplicare]=@DataPlanConturi AND b.CodUnitate = @CodUnitate AND pc.[TipUnitate]=b.TipUnitate                 
         WHERE  [Preluare] = 1 AND Terminal=0  AND Categorie=0
         ORDER BY [Cont]
	IF @@ERROR != 0 GOTO EROARE	

	PRINT('TERMINALE')
	--copiaza conturile terminale
	INSERT INTO [Conturi]([Cont],[Denumire],[Tip],[Terminal],[ContParinte],[EsteAnalitic],[Categorie],[CodUnitate],[DebitInitial],[CreditInitial],[DebitPrecedent],[CreditPrecedent],[RulajDebit] ,[RulajCredit])
		SELECT DISTINCT [Cont],[Denumire],[Tip],[Terminal],[ContParinte],0,[Categorie],@CodUnitate,0,0,0,0,0,0 FROM [PlanConturi] pc
         JOIN BalconSetup b ON [DataAplicare]=@DataPlanConturi AND b.CodUnitate = @CodUnitate AND pc.[TipUnitate]=b.TipUnitate                 
         WHERE  [Preluare] = 1 AND Terminal=1 AND Categorie=0
         ORDER BY [Cont]
    IF @@ERROR != 0 GOTO EROARE					
		
	COMMIT

	GOTO Gata
	EROARE:
		ROLLBACK
		RAISERROR ('Eroare la balcon_PopuleazaConturiUnitateNoua!',16,-1)
		GOTO Gata
	EROARE1:
		RAISERROR ('!!',16,-1)	
		GOTO Gata
	Gata:	
	
END